<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/4/28
 * Time: 13:52
 */
namespace app\bean;
class Bean
{
    /**
     * @param array $filterAttr
     * @return array
     */
    public function toArray(array $filterAttr = [])
    {
        $reflectClass = new \ReflectionClass($this);
        $properties = $reflectClass->getProperties();
        $arr = [];
        foreach ($properties as $property){
            $propertyName = $property->getName();
            if(in_array($propertyName,$filterAttr)){
                continue;
            }
            if($property->isPublic()){
                $arr[$propertyName] = $this->$propertyName;
            }
            $method = "get".implode("",explode("_",$propertyName));;
            if($reflectClass->hasMethod($method)){
                if($reflectClass->getMethod($method)->isPublic()){
                    $arr[$propertyName] = $this->$method();
                }
            }
        }
        return $arr;
    }

    /**
     * @param array $arr
     * @return \app\bean\Bean
     */
    public static function pollute(array $arr){
        $obj = new static();
        $reflectClass = new \ReflectionClass($obj);
        foreach($arr as $attr=>$val){
            $method = "set".implode("",explode("_",$attr));
            if($reflectClass->hasProperty($attr) &&  $reflectClass->hasMethod($method)){
                if($reflectClass->getMethod($method)->isPublic()){
                    $obj->$method($val);
                }
            }
        }
        return $obj;
    }
}